package com.gmaf.mas.launch.resloader;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gmaf.mas.launch.FilePathUtils;

public class FileResourceLoader implements ResourceLoader
{
	private static final Log log = LogFactory.getLog(FileResourceLoader.class);
	
	private String baseName = null;
	public FileResourceLoader(String base)
	{
		this.baseName = base;
	}
	public FileResourceLoader()
	{
		this(null);
	}
	
	@Override
	public URL getResource(String name)
	{
		File file = buildFile(name);
		
		if(file != null && file.exists())
		{
			try
			{
				return file.toURI().toURL();
			}
			catch(MalformedURLException e)
			{
				log.warn("Could not obtain URL from file: " + file.getAbsolutePath(), e);
			}
		}
		
		return null;
	}

	private File buildFile(String fileName)
	{
		if(fileName == null || StringUtils.isEmpty(baseName))
		{
			return null;
		}
		File file = new File(fileName);
		if(file.isAbsolute())
		{
			return file;
		}
		else
		{
			file = new File(baseName + File.separator + fileName);
			return FilePathUtils.getCanonicalFile(file);
		}
	}
	
	public String toString()
	{
		if(StringUtils.isEmpty(baseName))
		{
			return "FileResourceLoader: baseName=null";
		}
		File file = new File(baseName);
		return "FileResourceLoader: baseName=" + FilePathUtils.getCanonicalPath(file);
	}
}
